package com.wx.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wx.domain.Order;
import com.wx.domain.Patient;
import com.wx.service.OrderService;
import com.wx.service.PatientService;
import com.wx.service.impl.OrderServiceImpl;
import com.wx.service.impl.PatientServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 27250
 */
public class ReservationServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");

        String user = req.getParameter("user");
        String doctorId = req.getParameter("doctorId");
        String dateTime = req.getParameter("dateTime");

//        System.out.println(user+doctorId+dateTime);

        Map<String,Object> map=new HashMap<>();
        ObjectMapper mapper=new ObjectMapper();

        OrderService orderService=new OrderServiceImpl();
        PatientService patientService=new PatientServiceImpl();

        int nowNumber = orderService.getNumberBydoctorIdAndDateTime(doctorId,dateTime);
        if(nowNumber==5){
            map.put("msg","你选择的日期人数已满！请择日再来");
            map.put("isTrue",false);
            mapper.writeValue(resp.getWriter(),map);
        }else {
            Patient patient = patientService.findByUsername(user);
            Order order = orderService.getOrderListByPatientIdAndDateTime(patient.getPatientId(),dateTime);
            if (order==null){
                int orderId=orderService.save(patient.getPatientId(),doctorId,dateTime);
                map.put("orderId",orderId);
                map.put("msg","预约成功，您的的预约单号为："+orderId);
                map.put("isTrue",true);
                mapper.writeValue(resp.getWriter(),map);
            }
            map.put("isTrue",false);
            map.put("msg","今天已经预约过了，请不要多次预约");
            mapper.writeValue(resp.getWriter(),map);
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
